﻿using Dao;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraGrid;
using HospitalErpData.MenuHelper;
using HospitalErpWinUI.GlobalVar;
using HospitalErpWinUI.WinFormUiHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace HospitalErpWinUI.hbos.sys.user.user
{
    public partial class main : RibbonForm
    {
        protected DaoHelper _helper;
        public List<Perm> _perms { get; set; }
        DataTable _user = new DataTable();
        //初始化绑定默认关键词（此数据源可以从数据库取）
        List<string> _groupsInit = new List<string>();
        List<string> _groupsChange = new List<string>();
        public main()
        {
            _helper = new DaoHelper();
            InitializeComponent();
        }

        #region 获取数据
        private DataTable LoadGroup()
        {
            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = "sysUserGroup_select";
            paramters.Add("user_id", G_User.user.User_id);
            serviceParamter.Paramters = paramters;

            return _helper.ReadDictForSql(serviceParamter);
        }
        private void Query()
        {
            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = "sysUser_select";
            paramters.Add("sj_id",G_User.user.User_id);
            paramters.Add("user_code", user_code.Text.Trim()); 
            paramters.Add("user_name", user_name.Text.Trim());
            char [] array={' '};
           // string [] strArray= userGroup_code.Text.Trim().Split(array);
            string[] strArray = System.Text.RegularExpressions.Regex.Split(userGroup_code.Text.Trim(), @"\s{1,}");
            paramters.Add("group_code", strArray[0]);
            serviceParamter.Paramters = paramters;

            DataTable dt = _helper.ReadSqlForDataTable(serviceParamter);
            dt.Columns.Add("checked", System.Type.GetType("System.Boolean"));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i]["checked"] = "false";
            }
            _user = dt;
            gridControl1.DataSource = _user;
           
        }
        private bool Delete(string user_code)
        {
            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = "sysUser_delete";
            paramters.Add("user_code", user_code);
            serviceParamter.Paramters = paramters;
            bool result = false;
            try
            {
                _helper.WirteSql(serviceParamter);
                result = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;

        }
        private bool SetPassword(string user_code)
        {
            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = "sysUserPwd_update";
            paramters.Add("Doc", "<root><record><user_code>" + user_code + "</user_code></record></root>");
            serviceParamter.Paramters = paramters;
            bool result = false;
            try
            {

                result = _helper.WirteSql(serviceParamter);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;

        }
        #endregion

        #region 其他
        private void Init()
        {

            DataTable groups = LoadGroup();
            for (int i = 0; i < groups.Rows.Count; i++)
            {
                _groupsInit.Add(groups.Rows[i][1].ToString());

            }
            userGroup_code.Properties.Items.AddRange(_groupsInit);
        }

        #endregion

        #region 事件
        private void sysUser_insert_Click(object sender, EventArgs e)
        {
            try
            { 
                 insert insertFrm = new insert(this._helper, this._perms);

                if (insertFrm.ShowDialog() == DialogResult.OK)
                {
                    Query();
                }
            }
            catch(Exception ex )
            {
                MessageForm.Exception(ex.Message);
            }
           
        }

        private void main_Load(object sender, EventArgs e)
        {
            Init();
        }

        private void userGroup_code_TextChanged(object sender, EventArgs e)
        {
            string text = this.userGroup_code.Text;
            this.userGroup_code.Properties.Items.Clear();
            this._groupsChange.Clear();
            foreach (var item in _groupsInit)
            {
                if (item.Contains(text))
                {
                    _groupsChange.Add(item);
                }
            }
            //combobox添加已经查到的关键词
            userGroup_code.Properties.Items.AddRange(_groupsChange.ToArray());

            //设置光标位置，否则光标位置始终保持在第一列，造成输入关键词的倒序排列
            this.userGroup_code.SelectionStart = this.userGroup_code.Text.Length;

            //保持鼠标指针原来状态，有时候鼠标指针会被下拉框覆盖，所以要进行一次设置。
            Cursor = Cursors.Default;
            if (_groupsChange.Count > 1)
                this.userGroup_code.ShowPopup();

        }

        private void sysUser_select_Click(object sender, EventArgs e)
        {
            try
            {
                Query();    
            }
            catch(Exception ex)
            {
                MessageForm.Exception(ex.Message);
            }
        }

        private void sysUser_delete_Click(object sender, EventArgs e)
        {
            bool value = false;
            string strSelected = string.Empty;

            try
            {
                List<string> users = new List<string>();
                for (int i = 0; i < gridView1.RowCount; i++)
                {
                    value = Convert.ToBoolean(gridView1.GetDataRow(i)["checked"]);
                    if (value)
                    {
                        string code = gridView1.GetDataRow(i)["user_code"].ToString();
                        users.Add(code);

                    }
                }
                if (users.Count == 0)
                {
                    MessageForm.Show("请选择要删除的数据!");
                    return;
                }
                if (MessageForm.ShowMsg("确认是否删除?", MsgType.YesNo) == DialogResult.Yes)
                {
                    foreach (string user in users)
                    {
                        if (!Delete(user))
                        {
                            return;
                        }
                    }
                    //       MessageForm.Show("操作成功!");
                    Query();
                }

            }
            catch (Exception ex)
            {
                MessageForm.Warning("此记录在其他地方已经引用，不能删除!", "警告");
            }


        }

        private void sysUserPwd_update_Click(object sender, EventArgs e)
        {
            bool value = false;
            string strSelected = string.Empty;

            try
            {
                List<string> users = new List<string>();
                for (int i = 0; i < gridView1.RowCount; i++)
                {
                    value = Convert.ToBoolean(gridView1.GetDataRow(i)["checked"]);
                    if (value)
                    {
                        string code = gridView1.GetDataRow(i)["user_code"].ToString();
                        users.Add(code);

                    }
                }
                if (users.Count == 0)
                {
                    MessageForm.Show("请选择要重置密码的用户!");
                    return;
                }

                foreach (string user in users)
                {
                    if (!SetPassword(user))
                    {
                        return;
                    }
                }
                //       MessageForm.Show("操作成功!");
                MessageForm.Show("密码重置为'888888',请尽快修改!");
                Query();


            }
            catch (Exception ex)
            {
                MessageForm.Exception(ex.Message);
            }

        }

        private void setGroup_Click(object sender, EventArgs e)
        {
            bool value = false;
            string  users = string.Empty;
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                value = Convert.ToBoolean(gridView1.GetDataRow(i)["checked"]);
                if (value)
                {
                    string code = gridView1.GetDataRow(i)["user_code"].ToString();
                    users += code;
                    users += ",";
                }
            }
            if (string.IsNullOrEmpty(users))
            {
                MessageForm.Warning("请选择一个或多个用户.");
                return;
            }
            users = users.Substring(0, users.Length - 1);
            js_listAll frm = new js_listAll(this._helper, this._perms, users);
            frm.ShowDialog();
        }

        private void repositoryItemHyperLinkEdit1_OpenLink(object sender, DevExpress.XtraEditors.Controls.OpenLinkEventArgs e)
        {
            if (gridView1.FocusedRowHandle != GridControl.InvalidRowHandle)
            {
                int index = gridView1.GetDataSourceRowIndex(gridView1.FocusedRowHandle);
                string code = _user.Rows[index]["user_code"].ToString();
                string name = _user.Rows[index]["user_name"].ToString();
                js_list frm = new js_list(this._helper, this._perms, code, name);
                if (frm.ShowDialog() == DialogResult.No)
                {
                    MessageForm.Warning("修改失败！");
                }
            }

          
        }

        private void repositoryItemHyperLinkEdit2_OpenLink(object sender, DevExpress.XtraEditors.Controls.OpenLinkEventArgs e)
        {
            if (gridView1.FocusedRowHandle != GridControl.InvalidRowHandle)
            {
                int index = gridView1.GetDataSourceRowIndex(gridView1.FocusedRowHandle);
                string url = _user.Rows[index]["user_code"].ToString();
                copy_perm frm = new copy_perm(this._helper, this._perms, url);

             
                if (frm.ShowDialog() == DialogResult.No)
                {
                    MessageForm.Warning("修改失败！");
                }

            }
        }

        private void repositoryItemHyperLinkEdit3_OpenLink(object sender, DevExpress.XtraEditors.Controls.OpenLinkEventArgs e)
        {
            if (gridView1.FocusedRowHandle != GridControl.InvalidRowHandle)
            {
                int index = gridView1.GetDataSourceRowIndex(gridView1.FocusedRowHandle);
                string url = _user.Rows[index]["user_code"].ToString();
                update frm = new update(this._helper, this._perms, url);
                if (frm.ShowDialog() == DialogResult.No)
                {
                    MessageForm.Warning("修改失败！");
                }
                Query();
            }
        }

        #endregion

        private void panelControl3_Paint(object sender, PaintEventArgs e)
        {

        }

        private void panelControl1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void panelControl2_Paint(object sender, PaintEventArgs e)
        {

        }

            
    }
}
